<?php

/**
 * Ez generálja a verseny oldalát.
 *
 * @author poli
 */
class TournamentPageGenerator extends BaseContentGenerator {

	public $tournamentId;
	/**
	 * Ezt mutatja éppen
	 * @var array
	 */
	public $tournament;

	/**
	 * Ha ez nem null, akkor ezt a hibaüzenetet rakja ki, és error módú sablont generál
	 * @var string
	 */
	public $errorMsg;

	private $_initialized = false;

	public function TournamentPageGenerator($context, $generatorId, $iniParams = null, $skipIniParamsUpdateFromRequest = false) {
		parent::BaseContentGenerator("TournamentPage", $context, $generatorId, $iniParams, $skipIniParamsUpdateFromRequest);
	}

	/**
	 * Mi most használjuk az iniParams tömbünket nagyon is! Úhygogy nosza, dolgozzuk fel
	 * belőle a dolgokat!
	 *
	 * @see site/contentGenerators/BaseContentGenerator#processSavedIniParams()
	 */
	public function processSavedIniParams($savedIniParams) {
		$this->_iniParams = $savedIniParams;
	}

	/**
	 * Hasonló a page enterPage metódusához. Akkor kerül meghívásra, amikor a
	 * content generátor képernyőre kerül először. Azaz: az előző kérésre adott
	 * válaszban még nem ő generálta a content-et
	 *
	 * Itt meg lehet valósítani mindenféle inicializálást, aminek csak egyszer kell
	 * lefutni amíg a generátor aktív.
	 *
	 */
	public function enterContentGenerator() {
		parent::enterContentGenerator();
	}

	/**
	 * Hasonló a page leavePage metódusához. Akkor kerül meghívásra amikor a user
	 * elhagyja a content generátort. Azaz eddig ő generálta a válaszokba a tartalmat, de
	 * most más valaki generálja.
	 *
	 * Itt meg lehet valósítani mindenféle cleanup dolgokat a kilépés kapcsán.
	 */
	public function leaveContentGenerator() {
		parent::leaveContentGenerator();

		unset($_SESSION['__tournamentreg_formdata']);
	}

	protected function _init() {
		if($this->_initialized || !is_null($this->errorMsg))
		return;
		$this->_initialized = true;

		$this->tournamentId = FunctionLibrary::getGetIntValueSmart("id", null);
		if(!is_null($this->tournamentId)) {
			try {
				$this->tournament = SiteDBHelper::getTournament($this->tournamentId, TextHandler::getCurrentLangcode());

			} catch (Exception $e) {
				$msg = "failed to read up tournament!";
				Log::error($msg);
				MailHelper::sendAdminMail("TournamentPageGenerator error", $msg);
					
				$this->errorMsg = TextHandler::getText("obj_brand_read_failed");
			}
		}			
	}

	public function serveRequest() {
		parent::serveRequest();

		$this->_init();

		if (is_null($this->tournament)) {
			$response = null;
			return $response;
		} else {
			SiteBase::addJavascript('site/js/tournamentScripts.js');
	
			$action = FunctionLibrary::getGetValue('action');
			if($action) {
				$action = 'action_'.$action;
				$this->$action();
			}
	
			$tpl = BaseContentGenerator::loadTemplateFile("tournament.tpl.html");
			TextHandler::insertTextsIntoTemplate($tpl);
			$tpl->setVariable('app_root_url', APP_ROOT_URL);
	
			if(!is_null($this->tournament)) {
				SiteBase::setPageTitle($this->tournament['name']);
				$tpl->setVariable('tournamentName', $this->tournament['name']);
				$tpl->setVariable('tournamentLocation', $this->tournament['location']);
				$tpl->setVariable('tournamentDate', TournamentHandler::formatDate($this->tournament['date_from']) . ' - ' . TournamentHandler::formatDate($this->tournament['date_to']));
				$ts = TextUtil::parseTimestampString($this->tournament['date_from'], "%Y-%m-%d %H:%M:%S");
				$month = intval(date('m', $ts));
				$year = intval(date('Y', $ts));
				$tpl->setVariable('tournamentMonthLink', HydraLinkProvider::getLink('tournamentMonthLink', array('month' => $month, 'year' => $year)));
				$article = SiteDBHelper::getDefaultTournamentArticle($this->tournament['id'], array(TextHandler::getCurrentLangcode(), 'en', $this->tournament['langcode']));
				if (! empty($article)) {
					$tpl->setVariable('articleLead', $article['lead']);
					$articleObj = Article::createFromDBRecord($article);
					// title nélkül legyen a cikk
					$articleTpl = BaseContentGenerator::loadTemplateFile("tournament_article.tpl.html");
					$body = ArticleHandler::generateArticleHtmlFromObject($articleObj, TextHandler::getCurrentLangcode(), $articleTpl);
					$tpl->setVariable('tournamentArticle', $body);
				} else {
					$tpl->setVariable('articleLead', '');
					$tpl->setVariable('tournamentArticle', '');
				}
				// regisztráció
				$ts = TextUtil::parseTimestampString($this->tournament['deadline'], "%Y-%m-%d %H:%M:%S");
				$ttypes = SiteDBHelper::getTournamentTypesOfTournament($this->tournamentId);
				if ($ts > time() && ! empty($ttypes)) {
					// értékek (pl. hibás kitöltés esetén)
					$defaultValues = $_SESSION['__tournamentreg_formdata'];
					// ha még nem járt le a határidő, és van versenyforma
					$ttypeForCombo = array();
					foreach ($ttypes as $ttype) {
						$ttypeForCombo[$ttype['id']] = $ttype['name'];
					}
					$tpl->setVariable('form_remark', (! isset($defaultValues['remark'])? '': $defaultValues['remark']));
					$ttypesHtml = FormUtil::getComboOptionHTMLTagsFromAssociativeArray($ttypeForCombo, $defaultValues['tournamentType']);
					$tpl->setVariable('form_comptypes', $ttypesHtml);
					// url
					$tpl->setVariable('regFormUrl', HydraLinkProvider::getLink('tournamentRegistrationLink', array('id' => $this->tournamentId)));
					// fields
					$count = (empty($defaultValues['names'])? 2: max(2, count($defaultValues['names'])));
					$fieldsHtml = new StringBuffer();
					for ($i = 0; $i < $count; $i++) {
						$values = null;
						if (! empty($defaultValues)) {
							$values = array();
							$values['name'] = $defaultValues['names'][$i];
							$values['email'] = $defaultValues['emails'][$i];
							$values['properties'] = $defaultValues['properties'][$i];
						}
						$fieldsTpl = TournamentHandler::getTournamentRegistrationFields($this->tournament, $values);
						$fieldsHtml->append($fieldsTpl->get());
					}
					$tpl->setVariable('fields', $fieldsHtml->toString());
					if (empty($defaultValues)) {
						$tpl->replaceBlock('scriptOpenRegistration', '');
					}
					$tpl->touchBlock('scriptOpenRegistration');
				} else {
					$tpl->replaceBlock('registration', '');
					$tpl->touchBlock('registration');
				}
			}
			return $tpl->get();
		}
	}

	function action_register() {
		$names = FunctionLibrary::getPostValue('names');
		$emails = FunctionLibrary::getPostValue('emails');
		$remark = FunctionLibrary::getPostValue('remark');
		$tournamentType = FunctionLibrary::getPostValue('ttype');
		$properties = TournamentHandler::getTournamentRegistrationData($this->tournament, $tournamentType);
		$_SESSION['__tournamentreg_formdata'] = array(
			'tournamentType' => $tournamentType,
			'remark' => $remark,
			'names' => $names,
			'emails' => $emails,
			'properties' => $properties
		);
		$redirectLink = HydraLinkProvider::getLink('tournamentLink', array('id' => $this->tournamentId));

		try {
			$this->checkData($tournamentType, $names, $emails, $properties);

			// db mentés
			SiteDBHelper::registerPlayers($this->tournamentId, $tournamentType, $names, $emails, $remark, $properties);
			unset($_SESSION['__tournamentreg_formdata']);

			// email küldés
			$site = SiteHandler::getCurrentSite();
			$variables = array(
				'comp' => $this->tournament['name'],
				'siteName' => $site->name
			);
			$recipients = TournamentHandler::getRecipientsForTournamentRegistrationEmail($names, $emails, $properties, $tournamentType);

			AlertHandler::sendEmailAlert('tournament_registration.tpl.email', $recipients, $variables);
			$variables['registered_names'] = implode(', ', $names);
			
			$recipient = new AlertRecipient();
			$recipient->sendHere = $this->tournament['email'];
			// rendező nyelve!!
			$ttype = SiteDBHelper::getTournamentType($tournamentType, $this->tournament['default_langcode'], true);

			$recipient->langcodes = array($this->tournament['default_langcode']);
			$recipient->variables = array('compType' => $ttype['name']);
			$recipients = array($recipient);

			AlertHandler::sendEmailAlert('tournament_registration_organizer.tpl.email', $recipients, $variables);

			handleSuccess(TextHandler::getText('comp_entry_success'), $redirectLink);
			exit();
		} catch (ParameterException $e) {
			$errorStrings = $e->getErrors();
		} catch (Exception $e) {
			$logErrorString = "adding registration failed";
			Log::error('following errors occured during operation: '.$logErrorString);
			$errorStrings = array($e->getMessage());
		}

		handleError(TextHandler::getParsedText('comp_entry_err', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $redirectLink);
		exit();
	}

	private function checkData($tournamentType, $names, $emails, $properties) {
		$e = new ParameterException();

		if (! is_numeric($tournamentType)) {
			$e->addError(TextHandler::getText('comp_entry_err_emptyttype'));
		}

		// ha kell email-t megadni, akkor check
		$tc = TournamentHandler::getTournamentConfiguration($this->tournament);
		$needEmailAlways = ($tc['needEmailAlways']? true: false);
		$isEmail = false;
		foreach ($emails as $email) {
			if (empty($email) && $needEmailAlways) {
				$e->addError(TextHandler::getText('comp_entry_err_emailalways'));
				break;
			} else if (! empty($email)) {
				$isEmail = true;
			}
		}
		if (! $isEmail && ! $needEmailAlways) {
			$e->addError(TextHandler::getText('comp_entry_err_emailone'));
		}

		// jelentkezők száma
		// TODO: versenyformától függjön. Egyéni: 1, páros: 2, csapat: 4!!
		$playerCount = 0;
		for ($i = 0; $i < count($names); $i++) {
			if (! empty($names[$i])) $playerCount++;
		}

		if ($playerCount < 2) $e->addError(TextHandler::getText('comp_entry_err_notenoughplayer'));

		if ($e->hasError()) throw $e;
	}

}
